﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VirtualOrg.Helper;

namespace VirtualOrg.Web
{
    public partial class Main : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoadUserProfile();
        }

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            using (DB.DbStoreDataContext dataContext = new DB.DbStoreDataContext())
            {
                bool loginSuccess = false;

                var result = dataContext.CheckUserLogin(txtLoginUsername.Text, txtLoginPassword.Text);
                SessionInfo sessionInfo = new SessionInfo();
                foreach (var item in result)
                {
                    sessionInfo.UserID = item.UserID;
                    sessionInfo.UserName = item.Username;
                    sessionInfo.FullName = item.FullName;
                    sessionInfo.ImagePath = item.ProfilePic;
                    loginSuccess = true;
                }

                if (loginSuccess)
                {
                    Response.Cookies.Add(new HttpCookie(SiteConstants.CookieName, SiteHelper.EncryptSession(sessionInfo)));
                    Response.Cookies[SiteConstants.CookieName].Expires = DateTime.Now.AddHours(1);
                }
                else
                {
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Invalid credentials!')", true);
                }

                Response.Redirect("~/User/Dashboard.aspx");
            }
        }

        private void LoadUserProfile()
        {
            try
            {
                if (Request.Cookies.AllKeys.Contains(SiteConstants.CookieName))
                {
                    SessionInfo sessionInfo = SiteHelper.DecryptSession(Request.Cookies[SiteConstants.CookieName].Value);
                    lblUserInfo.Text = "Hello, " + sessionInfo.FullName;
                    pnlUserInfo.Visible = true;
                    imgProfilePic.ImageUrl = string.Format("~/Content/Photos/ProfilePic/{0}", sessionInfo.ImagePath);
                    acreateaccount.Visible = false;
                }
                else
                {
                    pnlLogin.Visible = true;
                    lblUserInfo.Text = "Login";
                    acreateaccount.Visible = true;
                }
            }
            catch
            {
                pnlLogin.Visible = true;
                lblUserInfo.Text = "Login";
                acreateaccount.Visible = true;
            }
        }
    }
}